<template>
  <el-drawer
    title="分配权限"
    :visible="drawer"
    :direction="direction"
    :before-close="handleClose"
    :destroy-on-close="true"
    class="drawer"
    @close="cancel"
  >
    <div class="tree-main">
      <div class="main-header">
        <el-tree
          ref="treeRole"
          check-strictly
          class="tree"
          :data="data"
          show-checkbox
          node-key="id"
          :check-on-click-node="true"
          :default-expanded-keys="permIds"
          :default-checked-keys="permIds"
          :props="defaultProps"
          @check="getCheckedKey"
        />
      </div>
      <div class="main-footer">
        <el-button round type="warning" @click="confirm">确定</el-button>
        <el-button round type="info" @click="cancel">取消</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { getPermissionListAPI } from '@/api/permission'
import { assignPremAPI } from '@/api/role'
import { list2Tree } from '@/utils/tree'
export default {
  props: {
    drawer: {
      type: Boolean,
      default: false
    },
    permIds: {
      type: Array,
      default: () => []
    },
    roleId: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      direction: 'ltr',
      defaultProps: {
        children: 'children',
        value: 'id',
        label: 'name'
      },
      data: []
    }
  },
  created() {
    this.permissionsList()
  },
  methods: {
    // 关闭抽屉
    async handleClose(done) {
      await this.$confirm('确定要退出吗？')
      this.$emit('update:drawer', false)
      done()
    },
    // 获取权限列表
    async permissionsList() {
      const { data } = await getPermissionListAPI()
      const result = list2Tree(data, 0)
      this.data = result
    },
    // 确认
    async confirm() {
      const res = this.$refs.treeRole.getCheckedKeys()
      if (!res.length) return this.$message.error('请选择权限')
      this.roleId && (await assignPremAPI(this.roleId, res))
      this.$emit('update:drawer', false)
    },

    // 关闭抽屉
    cancel() {
      this.$emit('update:drawer', false)
    },
    // 获取选中的key
    getCheckedKey(obj, key) {
      this.$emit('pushPermIds', key.checkedKeys)
    }
  }
}
</script>

<style scoped lang="scss">
.drawer {
  .tree-main {
    position: relative;
    border-top: 2px solid #ebeef5;
    box-sizing: border-box;

    .main-header {
      padding-left: 20px;
      height: 500px;
      overflow-y: auto;
      &::-webkit-scrollbar {
        width: 6px;
        // display: none;
      }

      &::-webkit-scrollbar-track {
        background-color: #f5f5f5;
      }

      &::-webkit-scrollbar-thumb {
        background-color: skyblue;
        border-radius: 5px;
      }
    }
    .main-footer {
      display: flex;
      justify-content: center;
      align-items: center;
      box-sizing: border-box;
      height: 136px;
      border-top: 1px solid #ebeef5;
      width: 100%;
      background-color: #fff;
    }
  }
}
</style>
